#include"tcp.hpp"
#include<cassert>
#include<pthread.h>

void* thread_entry(void* arg)
{
  TcpSocket new_sock;
  long fd = (long)arg;
  new_sock.set(fd);
  while(1)
  {
    std::string buf;
    
    bool ret = new_sock.Recv(&buf);
    if(ret == false)
    {
      new_sock.Close();
      break;
     }
    std::cout<<"client say: "<<buf<<std::endl;
    buf.clear();

    std::cout<<"server say: ";
    fflush(stdout);
    std::cin>>buf;
    ret = new_sock.Send(buf);
    if(ret == false)
    {
      new_sock.Close();
      break;
    }
  }
}
void create_work(TcpSocket sock)
{
  pthread_t tid;
  //创建线程，让线程进行客户端与服务端之间的收发数据工作
  long Fd = sock.fd();
  int ret = pthread_create(&tid,NULL,thread_entry,(void*)Fd);
  if(ret!=0)
  {
    printf("pthread_create error\n");
    sock.Close();
    return;
  }
  pthread_detach(tid);  //分离线程，线程退出后自动释放资源
}
//服务端
int main(int argc,char* argv[])
{
  if(argc != 3)
  {
    printf("./ tcp_srv 192.168.2.2 9000\n");
    return -1;
  }
  //提取ip地址和端口
  std::string ip = argv[1];
  uint16_t port = std::stoi(argv[2]);
  //1. 创建套接字
  TcpSocket sock;
  assert(sock.Socket());

  //2. 绑定地址信息
  assert(sock.Bind(ip,port));

  //3. 监听
  assert(sock.Listen());

  while(1)
  {
    //4. 获取新连接
    TcpSocket new_sock;
    std::string cli_ip;
    uint16_t cli_port;
    bool ret = sock.Accept(&new_sock,&cli_ip,&cli_port);
    if(ret==false)
    {
      continue;
    }

    std::cout<<"new clinet: "<<cli_ip<<":"<<cli_port<<std::endl;
    //创建线程
    create_work(new_sock);

  }

  //6. 关闭套接字
  sock.Close();
  return -1;
}
